package com.hll.service;

import com.hll.dao.BookDao;
import com.hll.exception.ParameterException;
import com.hll.model.Book;
import com.hll.model.BookStatus;
import com.hll.model.Pagination;
import com.hll.util.StringUtil;

import java.util.List;

public class BookService {

    /**
     * 新增图书
     */
    public int save(Book book) throws ParameterException {

        ParameterException parameterException = new ParameterException();

        if (StringUtil.isEmpty(book.getName())) {
            parameterException.addErrorField("name", "请填写书名");
        }
        if (StringUtil.isEmpty(book.getAuthor())) {
            parameterException.addErrorField("author", "请填写作者");
        }
        if (parameterException.isErrorField()) {
            throw parameterException;
        }

        /*如果id大于0，说明是更新操作，否则就是新增操作*/
        BookDao bookDao = new BookDao();
        if (book.getId() > 0) {
            bookDao.update(book);
        } else {
            bookDao.add(book);
        }
        return book.getId();
    }

    /**
     * 查询所有的图书和数量
     * */
    public List<Book> query(int userId, BookStatus status, Pagination pagination) {

        BookDao bookDao = new BookDao();
        return bookDao.query(userId, status, pagination);
    }


    public int getMyBookCount(int userId, BookStatus status) {

        BookDao bookDao = new BookDao();
        return bookDao.getMyBookCount(userId, status);
    }


    public Book getById(int id) {
        BookDao bookDao = new BookDao();
        return bookDao.getById(id);
    }

    /**
     * 逻辑删除
     * @param id
     */
    public void deleteById(int id) {
        BookDao bookDao = new BookDao();
        bookDao.updateDeleted(id, 1);
    }
}